package com.itheima.controller.syslog;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.SysLog;

import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.List;

@WebServlet("/syslog/*")
public class SysLogServlet extends BaseServlet {

    /**
     * 查询所有日志和模糊查询
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        List<SysLog> list=null;
        //获取页面参数
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");
        String time = req.getParameter("time");

        //模糊搜索，调用业务层方法
        if (time != null) {
            list = sysLogService.findAll(pageNum, pageSize, time);
            System.out.println("=========");
            System.out.println(list);
        } else {
            //调用服务层方法，遍历数据,参数在服务层处理
            list = sysLogService.findAll(pageNum, pageSize);
        }
        //将数据封装到页面工具对象中
        PageInfo<SysLog> pageInfo = new PageInfo<>(list);
        //反馈数据给前端
        req.setAttribute("page", pageInfo);
        req.getRequestDispatcher("/pages/syslog/syslog-list.jsp").forward(req, resp);
    }

    /**
     * 根据id 删除日志
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    protected void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取前端参数
        String ids = req.getParameter("ids");
        //调用业务层方法
        Boolean flag = sysLogService.deleteByIds(ids);
        //转json字符串，响应给前端
        String json = mapper.writeValueAsString(flag);
        resp.getWriter().write(json);
    }

    /**
     * 导出报表
     * @param req
     * @param resp
     * @throws Exception
     */
    protected void downLoadSysLog(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //返回的数据类型为文件xlsx类型
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("日志导出表.xlsx".getBytes(), "iso8859-1");
        resp.addHeader("Content-Disposition", "attachment;fileName=" + fileName);

        //生成报告的文件，然后传递到前端页面
        ByteArrayOutputStream os = sysLogService.getReport();
        //获取产生响应的流对象
        ServletOutputStream sos = resp.getOutputStream();
        //将数据从原始的字节流对象中提取出来写入到servlet对应的输出流中
        os.writeTo(sos);
        //将输出流刷新
        sos.flush();
        os.close();
    }
}
